﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Chloe;
using Chloe.Ext.Intf;
using Ace.Data;
using Chloe.Ext;

using System.Collections.Concurrent;

namespace Ace.Application.Implements
{
    public class ObjectSpaceService : AppServiceBase, IObjectSpaceService
    {
        private static int _connectionCount = 100;
       

       

        private IContextSpace CreateOneContextSpace()
        {

            return OjbectSpaceFactory.CreateContext();
        }
        private static ConcurrentQueue<IContextSpace> _CSQueue;
 
        static ObjectSpaceService()
        {
            _connectionCount = int.Parse(Globals.Configuration["db:ConnectionCount"]);
            _CSQueue = new ConcurrentQueue<IContextSpace>();
        }
        public IContextSpace getContextSpace()
        {
            IContextSpace outcs;
            if (!_CSQueue.TryDequeue(out outcs))
            {
                outcs = CreateOneContextSpace();
            }
            if (outcs == null || outcs.getDbContext() == null)
                outcs = CreateOneContextSpace();
            return outcs;
        }
        public void returnContextSpace(IContextSpace item)
        {
            //在归还space时,如果有脏数据,应该清空
            if (item.dirtyList.Count > 0)
                item.dirtyList.Clear();
            if (_CSQueue.Count < _connectionCount)
                _CSQueue.Enqueue(item);
            
            item.ClearTrackCollection();
        }
    }
}
